package com.chunayev.numerology.gui;

import static com.chunayev.numerology.util.Constants.ALPHABETS_PROPERTIES;
import static com.chunayev.numerology.util.Constants.RESOURCE_BUNDLE;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.util.Map;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.border.TitledBorder;

/**
 * @author Sergey Chunayev
 */
public class NumerologyFrame extends JFrame {
    
    private static final Map<Character, Integer> ruCharToIndex = new HashMap<Character, Integer>();
    
    private static final long serialVersionUID = 6882809531082139920L;
    static {
        final String ruAlphabet = ALPHABETS_PROPERTIES
                .getProperty("ru.alphabet");
        final char[] ruAlphabetChars = ruAlphabet.toCharArray();
        
        for (int i = 0; i < ruAlphabetChars.length; i++) {
            ruCharToIndex.put(ruAlphabetChars[i], i + 1);
        }
    }
    
    private final JButton calculateButton;
    private final JTextArea statisticsArea;
    
    private final JTextArea textArea;
    
    /**
     * 
     */
    public NumerologyFrame() {
        super(RESOURCE_BUNDLE.getString("frame.title"));
        final Container c = getContentPane();
        
        final JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout(5, 5));
        
        final JPanel textAreasPanel = new JPanel(new BorderLayout());
        final JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
        final JPanel textAreaPanel = new JPanel(new BorderLayout(0, 0));
        textAreaPanel.setBackground(Color.white);
        textArea = new JTextArea(20, 30);
        textAreaPanel.add(new JScrollPane(textArea));
        textAreaPanel.setBorder(new TitledBorder(RESOURCE_BUNDLE
                .getString("frame.textAreaPanel.title")));
        splitPane.add(textAreaPanel);
        final JPanel statisticsPanel = new JPanel(new BorderLayout(0, 0));
        statisticsPanel.setBorder(new TitledBorder(RESOURCE_BUNDLE
                .getString("frame.statisticsPanel.title")));
        statisticsArea = new JTextArea(20, 40);
        statisticsPanel.add(new JScrollPane(statisticsArea));
        statisticsPanel.setBackground(Color.white);
        statisticsArea.setEditable(false);
        splitPane.add(statisticsPanel);
        textAreasPanel.add(splitPane);
        mainPanel.add(textAreasPanel, BorderLayout.CENTER);
        
        calculateButton = new JButton(new CalculateAction());
        mainPanel.add(calculateButton, BorderLayout.SOUTH);
        
        c.add(mainPanel);
        
    }
    
    private class CalculateAction extends AbstractAction {
        
        private static final long serialVersionUID = -6816892266670329728L;
        
        /**
         * 
         */
        public CalculateAction() {
            putValue(Action.NAME, RESOURCE_BUNDLE
                    .getString("action.calculate.name"));
            putValue(Action.MNEMONIC_KEY, KeyEvent.VK_C);
        }
        
        /*
         * (non-Javadoc)
         * @see
         * java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent
         * )
         */
        @Override
        public void actionPerformed(final ActionEvent e) {
            statisticsArea.setText("");
            final String text = textArea.getText().trim();
            final String[] rows = text.split("\n+");
            for (final String row : rows) {
                int rowSumm = 0;
                final String[] tokens = row.trim().split(
                        String.format("[^%s]+", ALPHABETS_PROPERTIES
                                .getProperty("ru.regexp")));
                if (tokens.length > 0) {
                    for (final String s : tokens) {
                        if (!s.isEmpty()) {
                            final char[] chars = s.toLowerCase().toCharArray();
                            final StringBuilder rowBuilder = new StringBuilder(
                                    String.format("%s: ", s));
                            int wordSumm = 0;
                            for (final Character c : chars) {
                                final Integer value = ruCharToIndex.get(c);
                                wordSumm += value;
                                rowBuilder
                                        .append(String.format("%d + ", value));
                            }
                            
                            rowBuilder.replace(rowBuilder.length() - 3,
                                    rowBuilder.length(), "");
                            rowSumm += wordSumm;
                            
                            statisticsArea.append(String.format(
                                    "%s = %d, Position: %d\n", rowBuilder
                                            .toString(), wordSumm,
                                    determinePosition(wordSumm)));
                        }
                    }
                }
                
                statisticsArea
                        .append(String
                                .format(
                                        "%s\t%s:%d, %s:%d\n\n",
                                        RESOURCE_BUNDLE
                                                .getString("statisticsArea.result.rowSumm.total.title"),
                                        RESOURCE_BUNDLE
                                                .getString("statisticsArea.result.rowSumm.total.summ.title"),
                                        rowSumm,
                                        RESOURCE_BUNDLE
                                                .getString("statisticsArea.result.rowSumm.total.position.title"),
                                        determinePosition(rowSumm)));
            }
        }
        
        private int determinePosition(final int number) {
            if (number <= 49) {
                return number;
            }
            
            final int mod = number % 49;
            
            if (mod == 0) {
                return 49;
            }
            
            return mod;
        }
    }
    
}
